import{reactive} from 'vue'

export class FileItem{
    fid:number;
    file_name:string;
    file_path:string;
    file_size:number;
    constructor(fid:number,file_path:string,file_name:string,file_size:number){
        this.fid=fid
        this.file_name=file_name
        this.file_path=file_path
        this.file_size=file_size
    }

    formattedSize(){
        const units=['B','KB','MB','GB','TB']
        let uid=0
        let size=this.file_size
        while (size>=1024) {
            size/=1024
            uid+=1
        }
      //  return [size.toFixed(0),units[uid]]
      return size.toFixed(0)+units[uid]
      }
}

export async function request_file_list(refresh=false,reactify=false):Promise<FileItem[]>{
    let api='api/download/files'+(refresh?'?refresh=true':'')
    const res= await fetch(api)
    const file_list:FileItem[]=await res.json()
    const item_list=file_list.map(item=>new FileItem(item.fid,item.file_path,item.file_name,item.file_size))
    // console.log('Get download list:',file_list)
    if (reactify){
        return item_list.map(reactive)
    }else{
        return item_list
    }
}

export async function remove_file_from_list(fid:number){
    const api='api/download/files/'+fid
    const res=await fetch(api,{
        method:'delete',
    })
    if (res.ok){
        return true
    }else{
        console.log('Remove file failed, status code:',res.status)
        return false
    }
}

export async function remove_all_from_list(){
    const api='api/download/files/all'
    const res= await fetch(api,{
        method:'delete'
    })
    if (res.ok){
        return true
    }else{
        console.error('Remove all failed, status code:',res.status)
        return false
    }
}

export function download_file(item:FileItem){
    const api='api/download/files/'+item.fid
    const a=document.createElement('a')
    a.setAttribute('download',item.file_name)   
    a.setAttribute('href',api) 
    a.click()
}

